package com.lc.railway.ui.fragment;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.railway.R;
import com.lc.railway.app.AppFragment;
import com.lc.railway.http.glide.GlideApp;
import com.lc.railway.http.request.IndexApi;
import com.lc.railway.http.response.IndexnBean;
import com.lc.railway.other.IntentKey;
import com.lc.railway.ui.activity.ElegantActivity;
import com.lc.railway.ui.activity.HomeActivity;
import com.lc.railway.ui.activity.NewsDeatailsActivity;
import com.lc.railway.ui.activity.NewsSecondaryActivity;
import com.lc.railway.ui.activity.SearchActivity;
import com.lc.railway.ui.activity.WebViewActivity;
import com.lc.railway.ui.adapter.ImageAdapter;
import com.lc.railway.ui.adapter.ItemImageAdapter;
import com.lc.railway.ui.adapter.SimpleTextAdapter;
import com.lc.railway.ui.dialog.FieldsDialog;
import com.lc.railway.util.CourseUtils;
import com.lc.railway.util.eventbus.Event;
import com.lc.railway.widget.MyViewPagerIndicator;
import com.lc.widget.layout.SettingBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xj.marqueeview.MarqueeView;
import com.xj.marqueeview.base.MultiItemTypeAdapter;
import com.youth.banner.Banner;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.indicator.RoundLinesIndicator;
import com.youth.banner.util.BannerUtils;
import com.youth.banner.util.LogUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CustomAdapt;

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18
 * desc   : 首页 Fragment
 */
public final class HomeFragment extends AppFragment<HomeActivity> implements CustomAdapt {
    @BindView(R.id.iv_home_search)
    ImageView ivHomeSearch;
    @BindView(R.id.img_logo)
    ImageView imgLogo;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.image_top)
    ImageView imageTop;

    @BindView(R.id.topLine)
    RelativeLayout topLine;
    @BindView(R.id.rv_class)
    RecyclerView rvClass;
    @BindView(R.id.rv_importantnews)
    RecyclerView rvImportantnews;
    @BindView(R.id.nestedscrollview)
    NestedScrollView nestedscrollview;
    @BindView(R.id.rv_nav)
    RecyclerView rvNav;
    @BindView(R.id.indicator_line)
    MyViewPagerIndicator indicatorLine;
    @BindView(R.id.mv_multi_text5)
    MarqueeView marqueeView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<IndexnBean.NavBean> navList = new ArrayList<>();
    private List<IndexnBean.ClassBean> classList = new ArrayList<>();
    private List<IndexnBean.IsShowBean> is_show = new ArrayList<>();
    private List<IndexnBean.NewsArrBean> news_arr = new ArrayList<>();
    private List<IndexnBean.BannerBean> bannerList = new ArrayList<>();
    private List<IndexnBean.GggongshiBean> ggongshiList = new ArrayList<>();
    private BaseQuickAdapter<IndexnBean.NavBean, BaseViewHolder> navadapter;
    private BaseQuickAdapter<IndexnBean.ClassBean, BaseViewHolder> classadapter;
    private BaseQuickAdapter<IndexnBean.NewsArrBean, BaseViewHolder> news_arradapter;
    private ImageAdapter banneradapter;
    private SimpleTextAdapter simpleTextAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initView() {
        LinearLayoutManager lm = new LinearLayoutManager(getContext());
        lm.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvNav.setLayoutManager(lm);

        navadapter = new BaseQuickAdapter<IndexnBean.NavBean, BaseViewHolder>(R.layout.item_nav, navList) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, IndexnBean.NavBean navBean) {
                holder.setText(R.id.tv_classname, navBean.getClassname());
                if (navBean.isGrop()) {
                    holder.setTextColorRes(R.id.tv_classname, R.color.main_color);
                    holder.setVisible(R.id.img_xiahua, true);
                } else {
                    holder.setTextColorRes(R.id.tv_classname, R.color.color70757C);
                    holder.setVisible(R.id.img_xiahua, false);
                }
            }

        };
        rvNav.setAdapter(navadapter);
        navadapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                for (IndexnBean.NavBean bean : navList) {
                    bean.setGrop(false);
                }
                IndexnBean.NavBean bean = navList.get(position);
                bean.setGrop(!bean.isGrop());
                navadapter.notifyDataSetChanged();
                if (bean.getClassname().equals("电子邮箱")){
                    startActivity(WebViewActivity.class);
                }else {
                    startActivity(new Intent(getContext(), NewsSecondaryActivity.class).putExtra("id", CourseUtils.readValueFromUrlStrByParamName(bean.getLinkurl(),"classid")+"").putExtra("title",bean.getClassname()));
                }

            }
        });
        rvClass.setLayoutManager(new GridLayoutManager(getContext(), 4));
        classadapter = new BaseQuickAdapter<IndexnBean.ClassBean, BaseViewHolder>(R.layout.item_class, classList) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, IndexnBean.ClassBean item) {
                holder.setText(R.id.tv_title, item.getClassname());
                GlideApp.with(getContext()).load(IntentKey.IMAGE + item.getPicurl()).apply(new RequestOptions().placeholder(R.mipmap.dynamic_icon).error(R.mipmap.dynamic_icon)).into(((ImageView) holder.getView(R.id.img_class)));

            }

        };
        rvClass.setAdapter(classadapter);
        classadapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
//                if (classList.get(position).getClassname().equals("警营风采")) {
//                    startActivity( ElegantActivity.class);
//                }else {
//                    startActivity( HonorListActivity.class);
//
//                }

                startActivity(new Intent(getContext(),NewsSecondaryActivity.class).putExtra("id",classadapter.getData().get(position).getId()+"").putExtra("title",classadapter.getData().get(position).getClassname()));

            }
        });
        banneradapter = new ImageAdapter(getContext(), IndexnBean.getTestData());
        banner.setAdapter(banneradapter)

//                                .addBannerLifecycleObserver(getActivity())//添加生命周期观察者
                .setIndicator(new CircleIndicator(getContext()))
                .setIndicatorGravity(IndicatorConfig.Direction.RIGHT)
                .setIndicator(new RoundLinesIndicator(getActivity()), false) //false  时候,不显示指示器
                .setIndicatorSelectedWidth((int) BannerUtils.dp2px(10))
                .setOnBannerListener((dataa, position) -> {

                    startActivity(new Intent(getContext(),NewsDeatailsActivity.class).putExtra("id",is_show.get(position).getId()+"").putExtra("title",is_show.get(position).getTitle()+"").putExtra("type","777"));
                });
        news_arradapter = new BaseQuickAdapter<IndexnBean.NewsArrBean, BaseViewHolder>(R.layout.item_importantnews, news_arr) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, IndexnBean.NewsArrBean newsArrBean) {
                SettingBar sb_product = holder.getView(R.id.sb_product);
                sb_product.setLeftText(newsArrBean.getClassname());
                ItemImageAdapter banneradapter = new ItemImageAdapter(getContext(), bannerList);
                Banner banner = holder.getView(R.id.rv_banner);

                if (holder.getAbsoluteAdapterPosition() == 0) {
                    banner.setVisibility(View.VISIBLE);
                    banner.setAdapter(banneradapter)

//                                .addBannerLifecycleObserver(getActivity())//添加生命周期观察者
                            .setIndicator(new CircleIndicator(getContext()))

                            .setIndicator(new RoundLinesIndicator(getActivity()), false) //false  时候,不显示指示器
                            .setOnBannerListener((dataa, position) -> {

                                LogUtils.d("position：" + position);
                            });
                } else {
                    holder.setGone(R.id.rv_banner, true);
                }
                RecyclerView rv_album = holder.getView(R.id.rv_album);
                BaseQuickAdapter<IndexnBean.NewsArrBean.YaowenBean, BaseViewHolder> yaoadapter = new BaseQuickAdapter<IndexnBean.NewsArrBean.YaowenBean, BaseViewHolder>(R.layout.item_test_group, newsArrBean.getArr()) {
                    @Override
                    protected void convert(@NotNull BaseViewHolder holder, IndexnBean.NewsArrBean.YaowenBean yaowenBean) {
                        holder.setText(R.id.tv_title, yaowenBean.getTitle());
                        holder.setText(R.id.tv_date, CourseUtils.timeStamp2Date(yaowenBean.getCreate_time(), "yyyy-MM-dd"));

                        if (CourseUtils.isNullOrEmpty(yaowenBean.getPicurl())){
                            holder.setGone(R.id.img_logo,true);
                        }else {
                            holder.setVisible(R.id.img_logo,true);
                        }

                        GlideApp.with(getContext()).load(IntentKey.IMAGE + yaowenBean.getPicurl()).error(R.drawable.image11).into(((ImageView) holder.getView(R.id.img_logo)));
//

                    }

//                    }
                };
                rv_album.setAdapter(yaoadapter);
                yaoadapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                        startActivity(new Intent(getContext(),NewsDeatailsActivity.class).putExtra("id",yaoadapter.getData().get(position).getId()+"").putExtra("title",newsArrBean.getClassname()).putExtra("content",yaoadapter.getData().get(position).getTitle()).putExtra("picurl",yaoadapter.getData().get(position).getPicurl()).putExtra("time",yaoadapter.getData().get(position).getCreate_time()));

                    }
                });
            }
        };
        rvImportantnews.setAdapter(news_arradapter);
        news_arradapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                if (news_arr.get(position).getClassname().equals("警营风采")) {
                    startActivity( ElegantActivity.class);
                }else {
                startActivity(new Intent(getContext(),NewsSecondaryActivity.class).putExtra("id",news_arr.get(position).getId()+"").putExtra("title",news_arr.get(position).getClassname()));
                }
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                // refreshLayout.finishRefresh();  简单的设置刷新完成
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getIndex();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                // refreshLayout.finishLoadMore();  //  简单的设置加载更多完成
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                //  加载更多的逻辑
            }
        });

        getIndex();

    }

    @Override
    protected void initData() {

    }

    private void getIndex() {
        EasyHttp.post(this)
                .api(new IndexApi())
                .request(new HttpCallback<IndexnBean>(this) {
                    @Override
                    public void onSucceed(IndexnBean data) {
                        navList.clear();
                        navList.addAll(data.getNav());

                        if (navList.size() > 0) {
                            navList.get(0).setGrop(true);
                        }
                        navadapter.setNewData(navList);
                        navadapter.notifyDataSetChanged();
                        classList.clear();
                        classList.addAll(data.getClassX());
                        classadapter.setNewData(classList);
                        classadapter.notifyDataSetChanged();
//

                        is_show.clear();
                        is_show.addAll(data.getIs_show());
                        banneradapter.updateData(is_show);
                        //设置指示器
                        indicatorLine.setViewPager(banner.getViewPager2(), is_show.size(), true);
                        news_arr.clear();
                        news_arr.addAll(data.getNews_arr());
                        news_arradapter.setNewData(news_arr);
                        news_arradapter.notifyDataSetChanged();
                        bannerList.clear();
                        bannerList.addAll(data.getBanner());
                        ggongshiList.clear();
                        ggongshiList.addAll(data.getGggongshi());
                        simpleTextAdapter = new SimpleTextAdapter(getContext(), ggongshiList);
                        marqueeView.setAdapter(simpleTextAdapter);
                        simpleTextAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(int position, View view) {
                                startActivity(new Intent(getContext(),NewsDeatailsActivity.class).putExtra("id",ggongshiList.get(position).getId()+"").putExtra("title",ggongshiList.get(position).getTitle()+"").putExtra("type","888"));
                                if (marqueeView.isStart()) {
                                    marqueeView.stopFilp();
                                } else {
                                    marqueeView.startFlip();
                                }

                            }
                        });


                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });


    }


    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);


    }

    @OnClick({R.id.iv_home_search, R.id.img_more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_home_search:
                startActivity(SearchActivity.class);
                break;
            case R.id.img_more:
                FieldsDialog dialog=new FieldsDialog(getContext(),"首页");
                dialog.show();
                break;
        }
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

    @Override
    public float getSizeInDp() {
        return 667;
    }
}